package com.dries.security.core.social.wechat.api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.dries.security.common.exception.ApiException;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/17 10:09
 */
public class WeChatImpl extends AbstractOAuth2ApiBinding implements WeChat  {

    /**
     * 获取用户信息的URL
     */
    private static final String GET_WECHAT_USER_INFO = "https://api.weixin.qq.com/sns/userinfo?openid=%s";

    public WeChatImpl(String accessToken){
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
    }

    /**
     * 默认注册的StringHttpMessageConverter字符集为ISO-8859-1，而微信返回的是UTF-8的，所以覆盖了原来的方法。
     **/
    protected List<HttpMessageConverter<?>> getMessageConverters(){
        List<HttpMessageConverter<?>> messageConverters = super.getMessageConverters();
        messageConverters.remove(0);
        messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return messageConverters;
    }

    @Override
    public WeChatUserInfo getUserInfo(String openId) {
        String url = String.format(GET_WECHAT_USER_INFO, openId);
        String response = getRestTemplate().getForObject(url, String.class);
        if (StrUtil.containsIgnoreCase(response, "errcode")) {
            return null;
        }

        WeChatUserInfo profile = null;
        try {
            profile = JSONUtil.toBean(response, WeChatUserInfo.class);
            return profile;
        } catch (Exception e) {
            throw new ApiException("获取用户信息失败！", e);
        }
    }
}
